import { useEffect, useState } from 'react';
import Styles from './index.module.scss';

interface IProps {
  time: number;
  onEnd: Function;
}

const CountDown = ({ time, onEnd }: IProps) => {
  const [count, setCount] = useState(time || 60);

  useEffect(() => {
    const timer = setInterval(() => {
      setCount((count) => {
        if (count === 0) {
          clearInterval(timer);
          onEnd?.();
          return count;
        }
        return count - 1;
      });
    }, 1000);

    return () => clearInterval(timer);
  }, [time, onEnd]);

  return <div className={Styles.countDown}>{count}</div>;
};

export default CountDown;
